package com.shennan.oss.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.shennan.oss.service.OssService;
import com.shennan.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
public class OssServiceImpl implements OssService {


    @Override
    public String uploadFileAvatar(MultipartFile file) {

        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        //创建oss实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String url = null;

        try{

            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();

            //获取文件名称
            String fileName = file.getOriginalFilename();



            //文件按照日期进行分类
            //2021/11/11

            String datePath = new DateTime().toString("yyyy/MM/dd");

            //拼接
            fileName = datePath +"/"+ fileName;

            //调用oss方法实现上传
            ossClient.putObject(bucketName, fileName, inputStream);

            //关闭OSSCilent
            ossClient.shutdown();

            //把上传文件的路径返回
            //需要把上传阿里云的路径手动拼接出来
            url = "https://"+bucketName+"."+endpoint+"/"+fileName;


        }catch (IOException ce) {
            System.out.println("Error Message: " + ce.getMessage());
        }

        return url;
    }
}
